package com.zhenyi.websocket.core.ws;

import com.jfinal.kit.LogKit;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public final class WSUtilsPro {
	private Integer port;
	private String path;

	private EventLoopGroup bossGroup = new NioEventLoopGroup();
	private EventLoopGroup workerGroup = new NioEventLoopGroup();
	private ServerBootstrap serverBootstrap = new ServerBootstrap();

	public WSUtilsPro(int port, String path, WebSocketChannelInitializer2 initializer) {
		this.path = path;
		this.port = port;
		serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
		initializer.setPath(path);
		serverBootstrap.childHandler(initializer);
	}

	public void stop() {
		workerGroup.shutdownGracefully();
		bossGroup.shutdownGracefully();
	}

	public void start() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					LogKit.info("********start " + port + " " + path);
					ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
					channelFuture.channel().closeFuture().sync();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					bossGroup.shutdownGracefully();
					workerGroup.shutdownGracefully();
				}
			}
		}).start();

	}
}
